package com.huilian.iotbox.admin.service.impl;


import com.huilian.iotbox.admin.service.SmsCodeService;
import com.huilian.iotbox.admin.service.UserService;
import com.huilian.iotbox.admin.service.WXMessageService;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 谢洛涛
 * @date 2020/10/27 15:54
 */
@Slf4j
@Service
public class SmsCodeServiceImpl implements SmsCodeService {
    @Autowired
    private WXMessageService wxMessageService;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Override
    public ServerResponse sendSmsCode(Integer id) {
        User user = userService.findUserById(id);

        // 是否订阅公众号 没有生成关注二维码, 关注更新用户openid,
        // 有直接发送公众号验证码
//        if (ObjectUtils.isEmpty(user.getSubscribe())|| !user.getSubscribe()) {
//            ParamQrCode paramQrCode = wxMessageService.getQrCodeParam("QR_SCENE", user.getId().toString(), 2590000);
//            return ServerResponse.createBySuccess(paramQrCode);
//        }
        if (StringUtils.isEmpty(user.getOpenId())){
            return ServerResponse.createByErrorMessage("获取openid失败");
        }

        String key = RedisKey.DAIFU_SMSCODE_ + id;
        String s = (String) redisCacheTemplate.opsForValue().get(key + "EXPR");
        if (!ObjectUtils.isEmpty(s)) {
            return ServerResponse.createByErrorMessage("验证码发送频繁!稍后重试");
        }
        redisCacheTemplate.delete(key);
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        log.info("验证码是: {}", sb);
        wxMessageService.sendSmsCodeMessage(sb.toString(), user); // 发送公众号验证码
        redisCacheTemplate.opsForValue().set(key, sb.toString(), 5, TimeUnit.MINUTES);
        redisCacheTemplate.opsForValue().set(key + "EXPR", "111", 1, TimeUnit.MINUTES);
        return ServerResponse.createBySuccess("已向公众号成功发送验证码");
    }
}
